//
//  AliHelper.m
//  sdkdemo iOS
//
//  Created by sandy on 2018/3/7.
//

#import <Foundation/Foundation.h>
#import "AliHelper.h"
#import <AlipaySDK/AlipaySDK.h>

#import "cocos2d.h"
#import "CCLuaBridge.h"
#import "CCLuaEngine.h"
static int handlerID;
@implementation AliHelper
+(void) aliPayItem:(NSDictionary*) dic
{
    NSString* sign = [dic objectForKey:@"sign"];
    handlerID = (int)[[dic objectForKey:@"listener"] integerValue];
    NSLog(@"addNotifiction sign=%@",sign);
    NSLog(@"addNotifiction handlerID=%d",handlerID);
    NSString *orderString = [NSString stringWithFormat:@"%@",sign];
    [[AlipaySDK defaultService] payOrder:orderString fromScheme:@"alisdkdemo" callback:^(NSDictionary *resultDic) {
        NSLog(@"reslut = %@",resultDic);
        /*
        memo = "";
        result = "{\"alipay_trade_app_pay_response\":{\"code\":\"10000\",\"msg\":\"Success\",\"app_id\":\"2017062607569111\",\"auth_app_id\":\"2017062607569111\",\"charset\":\"utf-8\",\"timestamp\":\"2018-03-08 10:42:23\",\"total_amount\":\"0.01\",\"trade_no\":\"2018030821001004430526687846\",\"seller_id\":\"2088721328716203\",\"out_trade_no\":\"521\"},\"sign\":\"C7Neem6bPwpngtkuOuRAwGFvzb4hAwnc1t1j+QG0LiJ2aAHNzp3zLXF9knaoMzOQy3b6aYFQaACfTFEUxy4QkxG92NcVEuY/uSgxqxisAZimIYh+UYJk0CD0pz2zBQ+LhWMS/Xkzf3MjAcnmSeL5YWde1hyK9jxqF7rJrKuGji0TGDruma8/syIBaEePoNetzv2ZT7Bbl3mqABiMmhfavJGwblHlra+YdP74SxlsmH0PtGGM+cJ2944MOj+WSz0oBLZCrgIkEkX30IwGQZMGNXYE8JOk6Ig8fd2Xkz0jMbBiJMNE4//maObWi63eb4DmNhWCXWOf2kWZ6enY335WOA==\",\"sign_type\":\"RSA2\"}";
        resultStatus = 9000;
        */
        [self aliPayResult:resultDic];
    }];
}

+(void) aliPayResult:(NSDictionary *)resultDic
{
    NSLog(@"AliHelper result = %@",resultDic);
    NSLog(@"AliHelper handlerID = %d",handlerID);
    cocos2d::LuaBridge::pushLuaFunctionById(handlerID);
    if ([[resultDic objectForKey:@"resultStatus"] isEqualToString:@"9000"]) {
        //支付成功
        cocos2d::LuaBridge::getStack()->pushInt(0);
    }else if ([[resultDic objectForKey:@"resultStatus"] isEqualToString:@"4000"]){
        //交易失败
        cocos2d::LuaBridge::getStack()->pushInt(1);
    }else if([[resultDic objectForKey:@"resultStatus"] isEqualToString:@"6001"]){
        //操作取消
        cocos2d::LuaBridge::getStack()->pushInt(2);
    }else if([[resultDic objectForKey:@"resultStatus"] isEqualToString:@"6002"]){
        //网络出错
        cocos2d::LuaBridge::getStack()->pushInt(3);
    }else if([[resultDic objectForKey:@"resultStatus"] isEqualToString:@"8000"]){
        //交易待确认
        cocos2d::LuaBridge::getStack()->pushInt(4);
    }
    //cocos2d::LuaBridge::getStack()->pushString("sucess");  //将需要传递给lua层的参数通过栈传递
    cocos2d::LuaBridge::getStack()->executeFunction(1);  //共有1个参数 (“oc传递给lua的参数”)，这里传参数 1
    cocos2d::LuaBridge::releaseLuaFunctionById(handlerID); //最后记得释放
}

@end
